package com.example.train.common.config.security.model;

import com.example.train.model.SysAdmin;
import com.example.train.model.SysRole;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * SpringSecurity需要的用户详情
 */
public class AuthUserDetail implements UserDetails {
    private SysAdmin sysAdmin;
    private List<SysRole> roleList;
    public AuthUserDetail(SysAdmin sysAdmin, List<SysRole> roleList) {
        this.sysAdmin = sysAdmin;
        this.roleList = roleList;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //返回当前用户的权限
        return this.roleList.stream()
                .map(r ->new SimpleGrantedAuthority(r.getName()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return sysAdmin.getPassword();
    }

    @Override
    public String getUsername() {
        return sysAdmin.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return sysAdmin.getStatus() != null && sysAdmin.getStatus().equals(1);
    }

    public String getTokenSalt(){
        return sysAdmin.getTokenSalt();
    }

    public boolean canUse(){
        return isEnabled() && isAccountNonExpired() && isAccountNonLocked() && isCredentialsNonExpired();
    }

    public SysAdmin getSysAdmin(){
        return this.sysAdmin;
    }

    public List<SysRole> getRoleList(){
        return this.roleList;
    }

}
